//
//  BldPresViewCtrl.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/11/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "BldPresViewCtrl.h"
#import "BldPresView.h"
#import "UIView+Extension.h"
#define DefaultColor [UIColor colorWithRed:0.83 green:0.00 blue:0.40 alpha:1.00]
@interface BldPresViewCtrl ()

@end

@implementation BldPresViewCtrl {
    UILabel* _lblMsg;
    
    UIImageView* _ivStartTip;
    BldPresView* _bldpCtrlView;
    UIButton* _btnStartStop;
    
    UIView* _ivhLine;
    UIView* _ivvLine;
    
    UILabel* _lblSysTips; ///hight
    UILabel* _lblDiaTips;
    
    UILabel* _lblSysVal; ///hight
    UILabel* _lblDiaVal;
    
    BOOL _bIsSuptBLe;
    BOOL _bStartBleMeas;
    NcitBleDevice* _ncitBleDev;
    
    //body info
    NSInteger _nBodyId;
    NSString* _sCurUserEmail;
    
    //meas data
    //NSInteger _nHrateId;
    //int _nCountTick;
    NSTimer* _measTimer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:0.128 green:0.128 blue:0.128 alpha:0.5];
    
    _nBodyId = 0;
    _sCurUserEmail = nil;
    _measTimer = nil;
    [self getUserRegInfo];
    
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //UIImage* iProf = [pApp getImageScale:@"ic-list.png" scale: 0.4];
    //UIBarButtonItem *profButton = [[UIBarButtonItem alloc] initWithImage:iProf style:UIBarButtonItemStylePlain target:self action:@selector(mainAction:)];
    //self.navigationItem.rightBarButtonItem = profButton;
    
    _ncitBleDev= pApp.m_ncitBleDev;
    _bIsSuptBLe = pApp.m_bSupportBle;
    
    CGRect frame = [[UIScreen mainScreen] bounds];
    CGFloat W = frame.size.width;
    CGFloat H = frame.size.height;
    
    
    CGFloat yPos = (H > 1000)? 85.0f: 120.0f;
    if(H <= 480)
        yPos -= 40;
    else if(H > 480 && W == 320)
         yPos -= 10;
    [self initViewCtrls:yPos scrWdt:W scrHgt:H];
    
    _bStartBleMeas = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    UIImage* imgback = [UIImage imageNamed:@"ic-mainbkgd2.png"];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:imgback]];
    
//  UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//  [btnBack setImage:[UIImage imageNamed:@"btn-left-w.png"] forState:UIControlStateNormal];//@"btn_back.png"
//  [btnBack addTarget:self action:@selector(onRtnMainPage:) forControlEvents:UIControlEventTouchUpInside];
//  
//  UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
//  self.navigationItem.leftBarButtonItem = btniBack;
}

- (void) initViewCtrls:(CGFloat) yPos scrWdt:(CGFloat) W scrHgt:(CGFloat)H
{
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
    BOOL bIpad = H > 1000;
    BOOL bWider = W > 320;
    BOOL bIp4s = H <= 480;
    
    UIImage* iStart = [UIImage imageNamed:@"ic-start-tips.png"];
    CGFloat fHgt = W * iStart.size.height / iStart.size.width;
    _ivStartTip = [[UIImageView alloc] initWithFrame:CGRectMake(0, yPos + (bIpad?20:2), W, fHgt)];
    [_ivStartTip setImage:iStart];
//    [self.view addSubview:_ivStartTip];
    
    fHgt = bIpad? H/ 2.0: H/ 1.8;
    _bldpCtrlView = [[BldPresView alloc] initWithFrame:CGRectMake(0, yPos + (bIpad?100:(bIp4s?10:30)) - 30, W, fHgt)];
    [self.view addSubview:_bldpCtrlView];
//    _bldpCtrlView.backgroundColor = [UIColor yellowColor];
    UIImage* iBtn = [[UIImage imageNamed:@"start-bp.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _btnStartStop = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnStartStop.frame = CGRectMake(W - (bIpad? 160: 100), yPos + (bIpad? H/2.2 :(bIp4s? H/2.6:H/2.4)) - 30, W / 9, W / 9);
    [_btnStartStop setImage:iBtn forState:UIControlStateNormal];
    [_btnStartStop addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnStartStop];
    _btnStartStop.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    UILabel *tipLable = [[UILabel alloc] init];
    tipLable.frame = CGRectMake(0, CGRectGetMaxY(_btnStartStop.frame) + 15, W / 3, 20);
    tipLable.centerX = _btnStartStop.centerX;
    tipLable.textColor = [UIColor blackColor];
    tipLable.font = [UIFont systemFontOfSize:11];
    tipLable.textAlignment = NSTextAlignmentCenter;
    tipLable.text = NSLocalizedString(@"Turn on device & Press Start", nil);
    [self.view addSubview:tipLable];
    
    
    CGRect rt;
    UIImage* iCon = [[UIImage imageNamed:@"ic-horline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  fHgt = iCon.size.height * 2 / 3;//W * iCon.size.height / iCon.size.width;
    rt.origin.x = 0;
    rt.origin.y = yPos + (H / 2.0) + (bIpad? 115: (bIp4s?40:(bWider?85:65))) - 30;
    rt.size.height = fHgt;
    rt.size.width = W;
    rt.size.height = 1.0;
    _ivhLine  = [[UIView alloc] initWithFrame:rt];
    _ivhLine.backgroundColor = [UIColor grayColor];
    _ivhLine.alpha = 0.7;
//    [_ivhLine setImage:iCon];
    [self.view addSubview:_ivhLine];
    
    iCon = [[UIImage imageNamed:@"ic-verline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
   fHgt = iCon.size.width / 2;
    rt.origin.x = W / 2.0 - fHgt / 2.0;
    rt.origin.y = rt.origin.y + 15;
    rt.size.height = H - rt.origin.y - 10;
    rt.size.width = fHgt;//iCon.size.width;
    _ivvLine  = [[UIView alloc] initWithFrame:CGRectMake(W / 2, CGRectGetMaxY(_ivhLine.frame), CGRectGetHeight(_ivhLine.frame), 500)];
    _ivvLine.backgroundColor = [UIColor grayColor];
    _ivvLine.alpha = 0.7;
//    [_ivvLine setImage:iCon];
    [self.view addSubview:_ivvLine];
    
    yPos = yPos + (H / 1.9) + (bIpad? 125: (bIp4s?40:(bWider?80:60)));
    yPos += bIpad? 110: 40;
//    _lblSysTips = [[UILabel alloc] initWithFrame:CGRectMake(20, yPos - 10, W/2-40, 25)];
    _lblSysTips = [[UILabel alloc] initWithFrame:CGRectMake(20, H / 18 * 16.6, W/2-40, 25)];
    _lblSysTips.textColor = DefaultColor;
    _lblSysTips.font = Semibold(14);
    _lblSysTips.backgroundColor = [UIColor clearColor];
    _lblSysTips.textAlignment = NSTextAlignmentCenter;
    _lblSysTips.text = NSLocalizedString(@"Current Systolic", nil);
    [self.view addSubview:_lblSysTips];
    
    _lblDiaTips = [[UILabel alloc] initWithFrame:CGRectMake(W/2 +20, yPos - 10, W/2-40, 25)];
    _lblDiaTips.textColor = DefaultColor;
    _lblDiaTips.font = Semibold(14);
    _lblDiaTips.backgroundColor = [UIColor clearColor];
    _lblDiaTips.textAlignment = NSTextAlignmentCenter;
    _lblDiaTips.text = NSLocalizedString(@"Current Diastolic", nil);
    _lblDiaTips.centerY = _lblSysTips.centerY;
    [self.view addSubview:_lblDiaTips];
    
//    _lblSysVal = [[UILabel alloc] initWithFrame:CGRectMake(20, yPos - 5, W/2-40, 50)];
    _lblSysVal = [[UILabel alloc] initWithFrame:CGRectMake(20, H / 9 * 7.2, W/2-40, 50)];
    _lblSysVal.textColor = [UIColor blackColor];
    _lblSysVal.font = [UIFont systemFontOfSize: 56.0];
    _lblSysVal.backgroundColor = [UIColor clearColor];
    _lblSysVal.textAlignment = NSTextAlignmentCenter;
    _lblSysVal.text = @"---";
    [self.view addSubview:_lblSysVal];
    
    _lblDiaVal = [[UILabel alloc] initWithFrame:CGRectMake(W/2 +20, yPos - 5, W/2-40, 50)];
    _lblDiaVal.textColor = [UIColor blackColor];
    _lblDiaVal.font = [UIFont systemFontOfSize: 56.0];
    _lblDiaVal.backgroundColor = [UIColor clearColor];
    _lblDiaVal.textAlignment = NSTextAlignmentCenter;
    _lblDiaVal.text = @"--";
    _lblDiaVal.centerY = _lblSysVal.centerY;
    [self.view addSubview:_lblDiaVal];

    
    _lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(20, bIp4s? 62:75, W-40, 25)];
    _lblMsg.textColor = DefaultColor;
    _lblMsg.font = Regular(15);
    _lblMsg.backgroundColor = [UIColor clearColor];
    _lblMsg.textAlignment = NSTextAlignmentCenter;
    //_lblMsg.text = [NSString stringWithFormat:@"Blood Pressure: Online for %@ %@", pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
    _lblMsg.text = NSLocalizedString(@"Blood Pressure: Online", nil);
    [self.view addSubview:_lblMsg];
}

- (void) viewWillDisappear:(BOOL)animated
{
    _ncitBleDev.bleDelegate = nil;
    [_ncitBleDev stopMeas];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  _lblMsg.text = NSLocalizedString(@"No enough memory!", nil);
  AudioServicesPlaySystemSound(1112);
}

- (void) didDiscoverPerServices:(CBPeripheral *)aPeripheral bleMgr:(CBCentralManager*)pBleMgr
{
  NSString* sName = aPeripheral.name;
  if ([sName isEqualToString:@"Bluetooth BP"] || [sName isEqual:@"Dual-SPP"]) {
    [pBleMgr connectPeripheral:aPeripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
                                                    forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
    [pBleMgr stopScan];
  }
}

- (void) getUserRegInfo
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    LoginBodyInfo* bodyInfo = pApp.m_bodyInfo;
    if(bodyInfo == nil)
        return;
    
   _nBodyId = bodyInfo.m_nBodyId;
    /*NSString* sLastName = bodyInfo.sLast;
    if(sFirstName.length > 0 || sLastName.length > 0)
     _sBodyName = [NSString stringWithFormat:@"%@ %@", sFirstName, sLastName];
     else
     _sBodyName = bodyInfo.sEmail;
     
     _nAgeYear = bodyInfo.nYearAge;
     _fBodyWgt = bodyInfo.fBodyWgt;
     if(bodyInfo == 2)
     _fBodyWgt *= _LbtoKg;
     
     _nHgtCm = bodyInfo.nHgtCm;
     _nSexNum = bodyInfo.nGender;
     _nExeLvl = bodyInfo.nActLvl;
     _UserCardNo = bodyInfo.m_sTagId;
     
     if(bodyInfo.nHgtUn == 2) {
     Byte nInch = (bodyInfo.fBodyHgt - (Byte)bodyInfo.fBodyHgt) * 12.0;
     _sBodyHgt = [NSString stringWithFormat:@"%ift %iin", (short)bodyInfo.fBodyHgt, nInch];
     }
     else {
     _sBodyHgt = [NSString stringWithFormat:@"%.3fm", bodyInfo.fBodyHgt];
     }*/
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) mainAction:(id)sender
{
    //_lblMsg.text = @"Profile page";
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"bodyProfViewCtrl"];
}

- (void) tapImgBtnView:(id)sender
{
  if(!_bStartBleMeas) {
    //test start
    //[self insertTestBldData];
    //return;
    //test end
        
    if(!_bIsSuptBLe) {
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"BLE Support？" message: NSLocalizedString(@"Maybe your iOS device not support BLE...", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
      [alertView show];
      _lblMsg.text = NSLocalizedString(NSLocalizedString(@"Device BLE Support?", nil), nil);
      _lblMsg.textColor = [UIColor redColor];
      AudioServicesPlaySystemSound(1112);
      return;
    }
    if(_nBodyId == 0) {
      _lblMsg.text = NSLocalizedString(@"No login, No function", nil); //NSLocalizedString(@"NoLoginTip", nil);
      _lblMsg.textColor = [UIColor redColor];
      AudioServicesPlaySystemSound(1112);
      return;
    }
    //_nCountTick = 0;
    //_bNeedStored = YES;
    //_bContBleDev = NO;

    _measTimer = [NSTimer scheduledTimerWithTimeInterval:8.00 target:self selector:@selector(onMeasTimer) userInfo:nil repeats:NO];
        
    [_ncitBleDev setConnBleName:nil];
    if(_ncitBleDev != nil) {
      _ncitBleDev.bleDelegate = self;
      //_bOpenScanSheet = NO;
      //_bLoadStoreDevice = NO;
      if(_ncitBleDev.bConnBleDev) {
        [_ncitBleDev stopMeas];
      }
            
      _ncitBleDev.bleDelegate = self;
      [_ncitBleDev startMeas:nil];
      _lblMsg.text = NSLocalizedString(@"Try to contact with your BLD device", nil);
    }
  }
  else {
    //test start
    /*_lblMsg.text = [NSString stringWithFormat:@"%i, %i, %i", 128, 82, 85];
    [_bldpCtrlView setBledMeasData:128 lPres:82 hRate:85];
    [_measTimer invalidate];
    _measTimer = nil;
    [self bleDisconnected];
    return;*/
    //test end
        
    if(_measTimer != nil) {
      [_measTimer invalidate];
      _measTimer = nil;
    }
      //eWgtAppDelegate *appDelegate = (eWgtAppDelegate *)[[UIApplication sharedApplication] delegate];
      //[appDelegate CloseScaleHost];
        
    if( _ncitBleDev.m_pBleDevPer != nil && _ncitBleDev.pBleDevChar != nil) {
      uint8_t val[6] = {0xFD, 0xFD, 0xFE, 0x06, 0x0D, 0x0A};
      NSData* valData = [NSData dataWithBytes:(void*)&val length:sizeof(val)];
      [_ncitBleDev.m_pBleDevPer writeValue:valData forCharacteristic:_ncitBleDev.pBleDevChar type:CBCharacteristicWriteWithResponse];
    }
        
    [_ncitBleDev stopScan];
    [_ncitBleDev stopMeas];
        
    [self bleDisconnected];
    _lblMsg.text = @"stop";
        
    //if(_measTimer != nil)
      //[_measTimer invalidate];
  }
}

- (void) onMeasTimer
{
    if(!_bStartBleMeas) {
        _lblMsg.text = NSLocalizedString(@"Please turn device on", nil);
        AudioServicesPlaySystemSound(1112);
    }
    if(_measTimer != nil) {
        [_measTimer invalidate];
        _measTimer = nil;
    }
    
    /*short lowerBound = 10;
    short upperBound = 180;
    short nBldpres = lowerBound + arc4random() % (upperBound - lowerBound);
     
    [_bldpCtrlView setPresVal:nBldpres];
    
     _lblMsg.text = [NSString stringWithFormat:@"BLD Pres = %i", nBldpres];*/
}


//ble delegate

- (void) sendDataToBleDev:(CBCharacteristic*)aChar
{
    uint8_t val[6] = {0xFD, 0xFD, 0xFA, 0x05, 0x0D, 0x0A};
        
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    //[_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    [_ncitBleDev.m_pBleDevPer writeValue:valData forCharacteristic:aChar type:CBCharacteristicWriteWithoutResponse];
    
    [NSThread sleepForTimeInterval:0.3];
    [_ncitBleDev.m_pBleDevPer writeValue:valData forCharacteristic:aChar type:CBCharacteristicWriteWithoutResponse];
}

- (void) bleDevConnected
{
    _bStartBleMeas = YES;
    
    _lblMsg.text = NSLocalizedString(@"BLE blood pressure device Connected", nil);//[NSString stringWithFormat: @"%@ %s", [aPeripheral name], "Connected"];
//    UIImage* iBtn = [UIImage imageNamed:@"stop-bp.png"];
    UIImage* iBtn =  [[UIImage imageNamed:@"stop-bp.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    [_btnStartStop setImage:iBtn forState:UIControlStateNormal];
    
    [_bldpCtrlView startMeas];
}

- (void) updateBldPreVal:(short)nPresVal
{
    _lblMsg.text = [NSString stringWithFormat:@"%i", nPresVal];
    [_bldpCtrlView setPresVal:nPresVal];
}

-(void) insertTestBldData
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* dtFmt = pApp.dtFmt;
    [dtFmt setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
    
    //store
    NSInteger nBodyId = pApp.m_bodyInfo.m_nBodyId;
    NSDate* dtMeas = [pApp.dtFmt dateFromString:@"09/01/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:120 bpl:80 hrt:75 date:dtMeas toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/02/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:121 bpl:81 hrt:76 date:dtMeas toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/16/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:110 bpl:70 hrt:75 date:dtMeas toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/17/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:115 bpl:75 hrt:75 date:dtMeas toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/18/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:120 bpl:80 hrt:75 date:dtMeas toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/19/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:125 bpl:85 hrt:75 date:dtMeas toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/20/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:135 bpl:95 hrt:75 date:dtMeas toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/21/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:120 bpl:80 hrt:75 date:dtMeas toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/22/2015 13:23:45"];
    [pApp insertBdpData:nBodyId bph:100 bpl:60 hrt:75 date:dtMeas toSvr:YES];
    
    [pApp.dtFmt setDateFormat:sInitDtFmt];
}

- (void) recvedBldPreVal:(Byte)nhPres lPres: (Byte)nlPres hRate:(Byte)nhRate
{
    _lblMsg.text = [NSString stringWithFormat:@"%i, %i, %i", nhPres, nlPres, nhRate];
    [_bldpCtrlView setBledMeasData:nhPres lPres:nlPres hRate:nhRate];
    
    [_ncitBleDev stopScan];
    [_ncitBleDev stopMeas];
    
    /*if(_bNeedStored) {
        _nCountTick = 0;
        _lblInfo.text = NSLocalizedString(@"measEnd", nil);
        //[_vBldPres setNeedsDisplay];
        
        [self saveBldPresData:nhPres lPresVal:nlPres hRate:nhRate];
        [_btnTurnoff setTitle:NSLocalizedString(@"Close", nil) forState:UIControlStateNormal];
        AudioServicesPlaySystemSound(1109);
    }*/
    [self bleDisconnected];
    
    //store
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp insertBdpData:pApp.m_bodyInfo.m_nBodyId bph:nhPres bpl:nlPres hrt:nhRate date:[NSDate date] toSvr:YES];
    
    _lblSysVal.text = [NSString stringWithFormat:@"%i", nhPres];
    _lblDiaVal.text = [NSString stringWithFormat:@"%i", nlPres];
}

- (void) bleDisconnected
{
  _bStartBleMeas = NO;
  _ncitBleDev.bleDelegate = nil;
  _lblMsg.text = NSLocalizedString(@"BLE Disconnected!", nil);
  UIImage* iBtn = [[UIImage imageNamed:@"start-bp.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  [_btnStartStop setImage:iBtn forState:UIControlStateNormal];
}
@end
